<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="学员姓名">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入学员姓名"
            clearable
            class="!w-[180px]"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model="filterForm.phone"
            placeholder="请输入手机号码"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="培训课程">
          <el-select
            v-model="filterForm.trainingId"
            placeholder="请选择培训课程"
            clearable
            class="!w-[180px]"
          >
            <el-option
              v-for="training in trainingOptions"
              :key="training.id"
              :label="training.title"
              :value="training.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学员状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            class="!w-[120px]"
          >
            <el-option label="已报名" value="enrolled" />
            <el-option label="学习中" value="learning" />
            <el-option label="已完成" value="completed" />
            <el-option label="已退课" value="dropped" />
          </el-select>
        </el-form-item>
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="filterForm.enrollDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline :icon="Download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <IconifyIconOffline :icon="User" />
            </div>
            <div class="stat-info">
              <div class="stat-title">总学员数</div>
              <div class="stat-value">{{ studentStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon learning-icon">
              <IconifyIconOffline :icon="BookOpen" />
            </div>
            <div class="stat-info">
              <div class="stat-title">学习中</div>
              <div class="stat-value">{{ studentStats.learning }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon completed-icon">
              <IconifyIconOffline :icon="Trophy" />
            </div>
            <div class="stat-info">
              <div class="stat-title">已完成</div>
              <div class="stat-value">{{ studentStats.completed }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rate-icon">
              <IconifyIconOffline :icon="TrendingUp" />
            </div>
            <div class="stat-info">
              <div class="stat-title">完成率</div>
              <div class="stat-value">{{ studentStats.completionRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学员列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学员列表</span>
          <el-button type="primary" @click="handleAdd">
            <IconifyIconOffline :icon="Plus" />
            新增学员
          </el-button>
        </div>
      </template>
      
      <el-table :data="studentList" style="width: 100%" stripe v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="学员ID" width="80" />
        <el-table-column prop="name" label="学员姓名" width="120" />
        <el-table-column prop="phone" label="手机号码" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="trainingTitle" label="培训课程" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="学员状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="学习进度" width="120" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :stroke-width="8"
              :show-text="false"
              :color="getProgressColor(row.progress)"
            />
            <div class="progress-text">{{ row.progress }}%</div>
          </template>
        </el-table-column>
        <el-table-column prop="enrollDate" label="报名时间" width="110">
          <template #default="{ row }">
            {{ formatDate(row.enrollDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="completedDate" label="完成时间" width="110">
          <template #default="{ row }">
            {{ row.completedDate ? formatDate(row.completedDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="考试成绩" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.score !== null" :class="getScoreClass(row.score)">
              {{ row.score }}分
            </span>
            <span v-else class="text-gray-400">未考试</span>
          </template>
        </el-table-column>
        <el-table-column prop="certificate" label="证书状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.certificate" type="success" size="small">
              已颁发
            </el-tag>
            <el-tag v-else type="info" size="small">
              未颁发
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <IconifyIconOffline :icon="View" />
              查看
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              <IconifyIconOffline :icon="Edit" />
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 'completed' && !row.certificate"
              link 
              type="success" 
              size="small" 
              @click="handleIssueCertificate(row)"
            >
              <IconifyIconOffline :icon="Award" />
              颁发证书
            </el-button>
            <el-popconfirm
              title="确定要删除这个学员吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button link type="danger" size="small">
                  <IconifyIconOffline :icon="Delete" />
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 学员详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学员详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentStudent" class="student-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学员姓名">{{ currentStudent.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ currentStudent.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ currentStudent.email }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentStudent.idCard || '-' }}</el-descriptions-item>
          <el-descriptions-item label="培训课程">{{ currentStudent.trainingTitle }}</el-descriptions-item>
          <el-descriptions-item label="学员状态">
            <el-tag :type="getStatusTagType(currentStudent.status)" size="small">
              {{ getStatusText(currentStudent.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学习进度">
            <el-progress
              :percentage="currentStudent.progress"
              :stroke-width="8"
              :color="getProgressColor(currentStudent.progress)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="考试成绩">
            <span v-if="currentStudent.score !== null" :class="getScoreClass(currentStudent.score)">
              {{ currentStudent.score }}分
            </span>
            <span v-else class="text-gray-400">未考试</span>
          </el-descriptions-item>
          <el-descriptions-item label="报名时间">{{ formatDate(currentStudent.enrollDate) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentStudent.completedDate ? formatDate(currentStudent.completedDate) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="证书状态">
            <el-tag v-if="currentStudent.certificate" type="success" size="small">
              已颁发
            </el-tag>
            <el-tag v-else type="info" size="small">
              未颁发
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentStudent.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 学习记录 -->
        <div class="mt-4">
          <h4>学习记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="record in currentStudent.learningRecords"
              :key="record.id"
              :timestamp="formatDateTime(record.createTime)"
            >
              {{ record.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑学员弹窗 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑学员' : '新增学员'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="studentForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="学员姓名" prop="name">
              <el-input v-model="studentForm.name" placeholder="请输入学员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="studentForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="studentForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="studentForm.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="培训课程" prop="trainingId">
          <el-select v-model="studentForm.trainingId" placeholder="请选择培训课程" class="w-full">
            <el-option
              v-for="training in trainingOptions"
              :key="training.id"
              :label="training.title"
              :value="training.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学员状态" prop="status">
          <el-select v-model="studentForm.status" placeholder="请选择状态" class="w-full">
            <el-option label="已报名" value="enrolled" />
            <el-option label="学习中" value="learning" />
            <el-option label="已完成" value="completed" />
            <el-option label="已退课" value="dropped" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习进度" prop="progress">
          <el-slider v-model="studentForm.progress" :max="100" show-input />
        </el-form-item>
        <el-form-item label="考试成绩" prop="score">
          <el-input-number
            v-model="studentForm.score"
            :min="0"
            :max="100"
            placeholder="请输入考试成绩"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="studentForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import User from "@iconify-icons/ep/user";
import BookOpen from "@iconify-icons/ep/reading";
import Trophy from "@iconify-icons/ep/trophy";
import TrendingUp from "@iconify-icons/ep/trend-charts";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import Plus from "@iconify-icons/ep/plus";
import View from "@iconify-icons/ep/view";
import Edit from "@iconify-icons/ep/edit";
import Delete from "@iconify-icons/ep/delete";
import Award from "@iconify-icons/ep/medal";
import dayjs from "dayjs";

defineOptions({
  name: "TrainingStudent"
});

// 筛选表单
const filterForm = ref({
  name: "",
  phone: "",
  trainingId: "",
  status: "",
  enrollDateRange: []
});

// 学员统计
const studentStats = ref({
  total: 156,
  learning: 89,
  completed: 52,
  completionRate: 78.5
});

// 培训课程选项
const trainingOptions = ref([
  { id: 1, title: "羽毛球基础培训" },
  { id: 2, title: "乒乓球进阶课程" },
  { id: 3, title: "网球专业训练" },
  { id: 4, title: "篮球技巧提升" },
  { id: 5, title: "游泳入门教学" }
]);

// 学员列表
const studentList = ref([]);
const loading = ref(false);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 弹窗控制
const detailDialogVisible = ref(false);
const formDialogVisible = ref(false);
const isEdit = ref(false);
const submitLoading = ref(false);

// 当前学员
const currentStudent = ref(null);

// 学员表单
const studentForm = ref({
  id: "",
  name: "",
  phone: "",
  email: "",
  idCard: "",
  trainingId: "",
  status: "enrolled",
  progress: 0,
  score: null,
  remark: ""
});

// 表单引用
const formRef = ref();

// 表单验证规则
const formRules = {
  name: [{ required: true, message: "请输入学员姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ],
  trainingId: [{ required: true, message: "请选择培训课程", trigger: "change" }],
  status: [{ required: true, message: "请选择学员状态", trigger: "change" }]
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    enrolled: "info",
    learning: "warning",
    completed: "success",
    dropped: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    enrolled: "已报名",
    learning: "学习中",
    completed: "已完成",
    dropped: "已退课"
  };
  return statusMap[status] || status;
};

// 获取进度颜色
const getProgressColor = (progress: number) => {
  if (progress < 30) return "#f56c6c";
  if (progress < 70) return "#e6a23c";
  return "#67c23a";
};

// 获取成绩样式类
const getScoreClass = (score: number) => {
  if (score >= 90) return "text-green-600 font-bold";
  if (score >= 80) return "text-blue-600 font-bold";
  if (score >= 60) return "text-orange-600 font-bold";
  return "text-red-600 font-bold";
};

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 生成模拟数据
const generateMockData = () => {
  const mockData = [];
  const names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"];
  const statuses = ["enrolled", "learning", "completed", "dropped"];
  
  for (let i = 1; i <= 50; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const progress = status === "completed" ? 100 : Math.floor(Math.random() * 100);
    const score = status === "completed" ? Math.floor(Math.random() * 40) + 60 : null;
    const trainingId = Math.floor(Math.random() * 5) + 1;
    const training = trainingOptions.value.find(t => t.id === trainingId);
    
    mockData.push({
      id: i,
      name: names[Math.floor(Math.random() * names.length)] + i,
      phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      email: `student${i}@example.com`,
      idCard: `${Math.floor(Math.random() * 900000) + 100000}${Math.floor(Math.random() * 90) + 10}${Math.floor(Math.random() * 9000) + 1000}`,
      trainingId,
      trainingTitle: training?.title || "",
      status,
      progress,
      score,
      certificate: status === "completed" && Math.random() > 0.3,
      enrollDate: dayjs().subtract(Math.floor(Math.random() * 90), 'day').format('YYYY-MM-DD'),
      completedDate: status === "completed" ? dayjs().subtract(Math.floor(Math.random() * 30), 'day').format('YYYY-MM-DD') : null,
      remark: `学员${i}的备注信息`,
      learningRecords: [
        {
          id: 1,
          content: "学员报名成功",
          createTime: dayjs().subtract(Math.floor(Math.random() * 90), 'day').format('YYYY-MM-DD HH:mm:ss')
        },
        {
          id: 2,
          content: "开始学习课程",
          createTime: dayjs().subtract(Math.floor(Math.random() * 60), 'day').format('YYYY-MM-DD HH:mm:ss')
        },
        {
          id: 3,
          content: "完成第一阶段学习",
          createTime: dayjs().subtract(Math.floor(Math.random() * 30), 'day').format('YYYY-MM-DD HH:mm:ss')
        }
      ]
    });
  }
  return mockData;
};

// 搜索
const handleSearch = () => {
  loadStudentList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    name: "",
    phone: "",
    trainingId: "",
    status: "",
    enrollDateRange: []
  };
  loadStudentList();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 新增学员
const handleAdd = () => {
  isEdit.value = false;
  studentForm.value = {
    id: "",
    name: "",
    phone: "",
    email: "",
    idCard: "",
    trainingId: "",
    status: "enrolled",
    progress: 0,
    score: null,
    remark: ""
  };
  formDialogVisible.value = true;
};

// 查看学员详情
const handleView = (row: any) => {
  currentStudent.value = row;
  detailDialogVisible.value = true;
};

// 编辑学员
const handleEdit = (row: any) => {
  isEdit.value = true;
  studentForm.value = { ...row };
  formDialogVisible.value = true;
};

// 删除学员
const handleDelete = async (row: any) => {
  try {
    ElMessage.success(`已删除学员${row.name}`);
    loadStudentList();
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

// 颁发证书
const handleIssueCertificate = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认为学员${row.name}颁发培训证书吗？`,
      "颁发证书",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }
    );
    
    ElMessage.success(`已为学员${row.name}颁发证书`);
    loadStudentList();
  } catch (error) {
    // 用户取消
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
    formDialogVisible.value = false;
    loadStudentList();
  } catch (error) {
    console.error("表单验证失败", error);
  } finally {
    submitLoading.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadStudentList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadStudentList();
};

// 加载学员列表
const loadStudentList = async () => {
  try {
    loading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const mockData = generateMockData();
    studentList.value = mockData.slice(
      (pagination.currentPage - 1) * pagination.pageSize,
      pagination.currentPage * pagination.pageSize
    );
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载学员列表失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadStudentList();
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 20px;
      color: white;
      
      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.learning-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.completed-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.rate-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-text {
  text-align: center;
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.student-detail {
  h4 {
    margin: 20px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .main {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }
  
  .pagination-container {
    text-align: center;
  }
}
</style>